<?php

namespace app\controllers;

use Yii;
use app\models\Dept;
use app\models\DeptSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\controllers\GkyProfileController;
use app\models\GkyProfileSearch;

/**
 * DeptController implements the CRUD actions for Dept model.
 */
class DeptController extends Controller
{
//    public $layout='main_for_dept';
    public $layout='main_1';
    public function behaviors()
    {
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'rules' => [
                    [ 'allow' => true,'roles' => ['@'],],
                ],
            ],
            
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Dept models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new DeptSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $searchModel2 = new GkyProfileSearch();
        $dataProvider2 = $searchModel->search(Yii::$app->request->queryParams);
        
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Dept model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Dept model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Dept();
        $menus = $model->find()->all();
        //注意此处要先把find出来的AR对象变为普通数组 todo：直接查询出数组而不用AR
        $menus1 = \yii\helpers\ArrayHelper::toArray($menus);
        $menus2 = $this->toFormatTree($menus1);
        $menus3 = array_merge(array(0 => array('id' => 1, 'dname' => '顶级菜单', 'title_show' => '顶级菜单')), $menus2);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                 'menus' => $menus3,
            ]);
        }
    }

    /**
     * Updates an existing Dept model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        
        
        $modelDept = new Dept();
        $menus = $modelDept->find()->all();
        //注意此处要先把find出来的AR对象变为普通数组 todo：直接查询出数组而不用AR
        $menus1 = \yii\helpers\ArrayHelper::toArray($menus);
        $menus2 = $this->toFormatTree($menus1);
        $menus3 = array_merge(array(0 => array('id' => 1, 'dname' => '顶级菜单', 'title_show' => '顶级菜单')), $menus2);
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                   'menus' => $menus3,
            ]);
        }
    }

    /**
     * Deletes an existing Dept model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Dept model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Dept the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Dept::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    
    //以下拷贝自OneThink的TreeModel类

    /**
     * 把返回的数据集转换成Tree
     * @access public
     * @param array $list 要转换的数据集
     * @param string $pid parent标记字段
     * @param string $level level标记字段
     * @return array
     */
    public function toTree($list = null, $pk = 'serverid', $pid = 'parentserverid', $child = '_child') {
        if (null === $list) {
            // 默认直接取查询返回的结果集合
            $list = &$this->dataList;
        }
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();

            foreach ($list as $key => $data) {
                $_key = is_object($data) ? $data->$pk : $data[$pk];
                $refer[$_key] = & $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = is_object($data) ? $data->$pid : $data[$pid];
                $is_exist_pid = false;
                foreach ($refer as $k => $v) {
                    if ($parentId == $k) {
                        $is_exist_pid = true;
                        break;
                    }
                }
                if ($is_exist_pid) {
                    if (isset($refer[$parentId])) {
                        $parent = & $refer[$parentId];
                        $parent[$child][] = & $list[$key];
                    }
                } else {
                    $tree[] = & $list[$key];
                }
            }
        }
        return $tree;
    }

    /**
     * 将格式数组转换为树
     *
     * @param array $list
     * @param integer $level 进行递归时传递用的参数
     */
    private $formatTree; //用于树型数组完成递归格式的全局变量

    private function _toFormatTree($list, $level = 0, $title = 'dname') {
        foreach ($list as $key => $val) {
            $tmp_str = str_repeat("　", $level * 2);
            $tmp_str.="┝";
            $val['level'] = $level;
            $val['title_show'] = $level == 0 ? $val[$title] . "　" : $tmp_str . $val[$title] . "　";
            //$val['title_show'] = $val['id'].'|'.$level.'级|'.$val['title'];
            if (!array_key_exists('_child', $val)) {
                array_push($this->formatTree, $val);
            } else {
                $tmp_ary = $val['_child'];
                unset($val['_child']);
                array_push($this->formatTree, $val);
                $this->_toFormatTree($tmp_ary, $level + 1, $title); //进行下一层递归
            }
        }
        return;
    }

    public function toFormatTree($list, $title = 'dname', $pk = 'id', $pid = 'parentserverid', $root = 0) {
        $list = $this->list_to_tree($list, $pk, $pid, '_child', $root);
        $this->formatTree = array();
        $this->_toFormatTree($list, 0, $title);
        return $this->formatTree;
    }

    public static function list_to_tree($list, $pk = 'id', $pid = 'parentserverid', $child = 'items', $root = 0) {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] = & $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] = & $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent = & $refer[$parentId];
                        $parent[$child][] = & $list[$key];
                    }
                }
            }
        }
        return $tree;
    }
    
    
    
}
